package com.sq.util.web;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

/**
 * @author sq
 */
public class HttpPutUtil extends BaseHttpUtil {
    public static String execute(String url, Map<String, String> params) throws Exception {
        return execute(new HttpPut(url), params, null, StandardCharsets.UTF_8);
    }

    public static String execute(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        return execute(new HttpPut(url), headers, params, StandardCharsets.UTF_8);
    }

    public static String execute(String url, Map<String, String> params, Map<String, String> headers, Charset charset)
            throws Exception {
        return execute(new HttpPut(url), headers, params, charset);
    }

    public static String execute(String url, String content) throws Exception {
        return execute(new HttpPut(url), content, null, StandardCharsets.UTF_8);
    }

    public static String execute(String url, String content, Map<String, String> headers, Charset charset)
            throws Exception {
        return execute(new HttpPut(url), content, headers, charset);
    }

    /**
     * put请求，参数以form表单键值对的形式提交。
     */
    private static String execute(HttpPut httpPut, Map<String, String> params, Map<String, String> headers,
                                  Charset charset) throws Exception {
        setHeaders(httpPut, headers);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));
        return request(getHttpClient(), httpPut, charset);
    }

    /**
     * put请求，参数以原生字符串进行提交
     */
    private static String execute(HttpPut httpPut, String content, Map<String, String> headers, Charset charset)
            throws Exception {
        setHeaders(httpPut, headers);
        httpPut.setEntity(new StringEntity(content, charset));
        return request(getHttpClient(), httpPut, charset);
    }

}
